<script lang="ts">
    import { _ } from "svelte-i18n";
    import { Button } from "../Button";
    import Icon from "../Common/Icons/Icon.svelte";
    import { useClassList } from "../utils/useClassList";
    import List from "./List.svelte";
    import type { TransferProps, TransferStore } from "./Transfer";
    import { useFormItemContext } from "../FormItem/FormItem.svelte";

    let { value = $bindable([]), ...props }: TransferProps = $props();
    const ctx = useFormItemContext();
    const classList = $derived(useClassList(props, "cm-transfer"));

    const store = $state<TransferStore>({
        data: [],
        sourceDisabled: true,
        targetDisabled: true,
        sourceIds: [],
        targetIds: [],
    });

    const rightText = $derived(props.rightText || $_("Transfer.rightText"));
    const leftText = $derived(props.leftText || $_("Transfer.leftText"));

    $effect(() => {
        store.data = props.data || [];
    });

    const onSelect = (data: any, checked: boolean) => {
        if (!data.disabled) {
            const item = store.data.find((item) => item.id === data.id);
            if (item) {
                item._checked = checked;
            }
        }
    };

    const transferToTarget = () => {
        store.sourceIds.forEach((id: any) => {
            store.data.forEach((item) => {
                if (item.id === id) {
                    item._checked = false;
                }
            });
        });
        let v = value;
        v = v.concat([...store.sourceIds]);
        store.sourceIds = [];
        value = [...v];
        props.onchange?.([...v]);
        ctx?.onFieldChange?.();
    };

    const transferToSource = () => {
        store.targetIds.forEach((id: any) => {
            store.data.forEach((item) => {
                if (item.id === id) {
                    item._checked = false;
                }
            });
        });
        const v = value;
        store.targetIds.forEach((id: any) => {
            v.splice(v.indexOf(id), 1);
        });
        store.targetIds = [];
        value = [...v];
        props.onchange?.([...v]);
        ctx?.onFieldChange?.();
    };
</script>

<div class={classList} style={props.style}>
    <List width={props.width} height={props.height} {store} name="source" {value} {onSelect} filter={props.filter} render={props.render} title={props.sourceTitle} />
    <div class="cm-transfer-operation">
        <Button disabled={store.sourceDisabled} size="small" onclick={transferToTarget}>
            <Icon icon="chevronRight" size={14} />
            {rightText}
        </Button>
        <Button disabled={store.targetDisabled} size="small" onclick={transferToSource}>
            <Icon icon="chevronLeft" size={14} />
            {leftText}
        </Button>
    </div>
    <List width={props.width} height={props.height} {store} name="target" {value} {onSelect} filter={props.filter} render={props.render} title={props.targetTitle} />
</div>
